package base.json.fastjson.demo03;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Client {

    /**
     * Map -> JSONObject
     */
    @Test
    public void case1(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("age",101);
        map.put("name","张三");
        map.put("salary", 10000.0);
        map.put("birth", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        final String str = JSONObject.toJSONString(map);
        System.out.println("str: "+str);

        final JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println("jsonObject: "+jsonObject);

        final User user = JSONObject.parseObject(str, User.class);
        System.out.println("user: "+user);
    }

    /**
     * JSONObject -> Map
     */
    @Test
    public void case2(){
        String s = "{\"name\":\"张三\",\"birth\":\"2022-04-09 22:34:14\",\"salary\":10000.0,\"age\":101}";
        final JSONObject jsonObject = JSONObject.parseObject(s);
        final Map map = JSONObject.toJavaObject(jsonObject, Map.class);
        System.out.println(map);
//        JSONObject.parseObject(jsonObject, Map.class);
        final Map map1 = JSONObject.parseObject(s, Map.class);
    }

    /**
     * List -> JSONArray
     */
    @Test
    public void case3(){
        ArrayList<User> list = new ArrayList<>();
        list.add(new User("张三", 18));
        list.add(new User("李四", 19));

//         List<User> users = JSONObject.parseArray(JSONArray.toJSONString(list), User.class);
//         users = JSONArray.parseArray(JSONArray.toJSONString(list), User.class);
        JSONArray jsonArray = JSONObject.parseArray(JSONArray.toJSONString(list));
        jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        List<User> users = jsonArray.toJavaList(User.class);
        System.out.println(users);


        JSONObject jo1 = new JSONObject();
        jo1.put("name","zhangsan");
        JSONObject jo2 = new JSONObject();
        jo2.put("name","lisi");
        JSONArray ja = new JSONArray();
        ja.add(jo1);
        ja.add(jo2);
        System.out.println(ja);
    }


}
